from datetime import datetime, timedelta
from flask_security import login_required, login_user, logout_user, current_user
from flask_security.utils import verify_and_update_password
from flask_restplus import Resource
from werkzeug.exceptions import Unauthorized
from exlib.flask_restplus.resource import ActionResource
from exlib.flask_restplus.reqparse import RequestParser
from utils.decorators import anonymous_user_required
from app.user.models import User, Role
from app.user.serializers.user import UserSerializer, AuthInfoSerializer
from app.user.serializers.role import RoleSerializer
from app import api_base as api
from exlib.webbase.response import JsonResponse, SuccessResponse, FailedResponse, TableResponse


class AuthInfoView(ActionResource):
    @login_required
    def get(self):
        result = AuthInfoSerializer(current_user).data
        return SuccessResponse("成功返回userinfo", data=result)


class PasswordChangeView(Resource):
    poster = RequestParser()
    poster.add_argument('password', type=str, required=True, help='是否带产品线信息')

    @login_required
    @api.doc(description="修改个人密码")
    @api.expect(poster)
    def put(self):
        data = self.poster.parse_args()
        user = current_user
        user.reset_password(data['password'])
        user.save()
        # LogEntry.log('修改个人密码', current_user, user)
        return SuccessResponse(message='修改密码成功', data=UserSerializer(user).data)


class InfoChangeView(Resource):
    poster = RequestParser()
    poster.add_argument('email', type=str, required=True, help='必须填写email')

    @login_required
    @api.doc(description="修改个人信息")
    @api.expect(poster)
    def put(self):
        oriuser = current_user
        data = self.poster.parse_args()
        if data:
            oriuser.__data__.update(**data)
            User.edit_unique_check(oriuser)
            oriuser.save()
        return SuccessResponse(message='修改个人信息', data=UserSerializer(oriuser).data)


class LoginView(ActionResource):
    poster = RequestParser()
    poster.add_argument('name', type=str, required=True,help='name')
    poster.add_argument('password', type=str, required=True,help='password')

    @api.expect(poster)
    def post(self):
        """
            zhangsan/invest1234 新建用户默认密码为invest1234
        :return:
        """
        args = self.poster.parse_args()
        user = User.objects.filter(name=args.name).first()
        if not user:
            raise Unauthorized('登录失败，用户不存在: %s' % args.name)
        if not user.check_password_hash(args.password):
            raise Unauthorized('登录失败，密码错误: %s' % args.name)
        if not user.is_active:
            raise Unauthorized('登录失败，用户并非正常在职用户: %s' % user.cname)
        if login_user(user, remember=True):
            result = AuthInfoSerializer(current_user).data
            return SuccessResponse("成功登录", data=result)
        raise Unauthorized('登录失败')


class LogoutView(ActionResource):
    def get(self):
        logout_user()
        return SuccessResponse("已退出登录")
